package com.example.mybank.config;

import com.example.mybank.tool.ResultCode;
import com.example.mybank.tool.JsonResult;
import com.example.mybank.tool.MyException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(basePackages={"com.example.mybank.controller"})
public class UniformReponseHandler implements ResponseBodyAdvice {
    @ExceptionHandler(value = MyException.class)
    public JsonResult errorHandler(MyException e) {
        return new JsonResult(e.resultCode);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return JsonResult.ok(body);
    }
}
